package jbl.action;

import javax.servlet.http.HttpSession;

import jbl.pageModel.User;
import jbl.service.UserServiceI;
import jbl.util.Json;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

/**
 * 用户登录管理类
 */
@ParentPackage("login")
@Namespace("/login")
@Action(value="loginAction",results={@Result(name="index",location="/login.jsp"),@Result(name="success",location="/index.jsp")})
public class LoginAction extends BaseAction implements ModelDriven<User>{
	
	private User user=new User();
	private UserServiceI userService;
	
	public UserServiceI getuserService() {
		return userService;
	}
	@Autowired
	public void setUserService(UserServiceI userService) {
		this.userService = userService;
	}

	@Override
	public User getModel() {
		return user;
	}
	
	/**
	 * 查询登录
	 */
	public void checkLogin(){
		Json j = userService.checkLogin(user);
		writeJson(j);
	}
	
	/**
	 * 查询所有用户或条件查询
	 */
	public void DataGrid(){
		writeJson(userService.getDataGrid(user));
	}
	
	/**
	 * 添加用户
	 */
	public void addUser(){
		Json j=new Json();
		try {
			userService.addUser(user);
			j.setSuccess(true);
			j.setMsg("添加用户"+user.getUser()+"成功！");
		} catch (Exception e) {
			j.setMsg("添加用户"+user.getUser()+"失败！");
			e.printStackTrace();
		}
		writeJson(j);
	}
	
	/**
	 * 修改用户
	 */
	public void update(){
		Json j=new Json();
		try {
			userService.update(user);
			j.setSuccess(true);
			j.setMsg("更新用户"+user.getUser()+"成功！");
		} catch (Exception e) {
			j.setMsg("更新用户"+user.getUser()+"失败！");
			e.printStackTrace();
		}
		writeJson(j);
	}
	
	/**
	 * 删除用户
	 */
	public void delete(){
			Json j=new Json();
			try {
				userService.delete(user);
				j.setSuccess(true);
				j.setMsg("删除成功！");
			} catch (Exception e) {
				// TODO: handle exception
				j.setMsg("删除失败！");
			}
			writeJson(j);
	}
	
	/**
	 * 注销
	 */
	public void cancel(){
		Json j=new Json();
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(session!=null){
			session.invalidate();
		}
		j.setSuccess(true);
		writeJson(j);
		
	}
	/**
	 * 获取用户下拉列表值
	 */
	public void comboboxInfo(){
		writeJson(userService.comboboxInfo());
	}
}
